package com.xjscrm.console.chat.core.impl;

import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerMsgRecallMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.enums.ChatTalkRecordSource;
import com.xjscrm.console.chat.frame.recv.RRecallMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatRecallMsgHandler extends ChatBaseMsgHandler<RRecallMsg> {

    public static final String RECALL_KEY = "xj_msg_recall_%s";

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private ChatTalkRecordService chatTalkRecordService;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public SResultMsg doHandle(RRecallMsg content, ChannelHandlerContext ctx) {

        try {

            ChatTalkSession talkSession = chatTalkSessionService.getById(content.getMerId(), content.getTalkSessionId());

            if (Objects.isNull(talkSession)) {
                return SResultMsg.fail(content, "会话信息不存在, 请刷新后重试");
            }
            ChatTalkRecord talkRecord = chatTalkRecordService.getById(content.getMerId(), content.getRecordId());
            if (Objects.isNull(talkRecord) || Objects.isNull(talkRecord.getRemoteMsgId())) {
                return SResultMsg.fail(content, "聊天记录数据错误");
            }
            if (!Objects.equals(talkRecord.getSource(), ChatTalkRecordSource.reply.getCode())) {
                return SResultMsg.fail(content, "非回复消息, 不支持撤回");
            }
            int now = (int) (System.currentTimeMillis() / 1000L);
            if (Objects.isNull(talkRecord.getWxSendTime())) {
                return SResultMsg.fail(content, "回复消息数据错误");
            }
            if (now - talkRecord.getWxSendTime() > 120) {
                return SResultMsg.fail(content, "回复时间超过了两分钟不支持撤回");
            }

            MicaTriggerMsgRecallMsg msgRecallMsg = new MicaTriggerMsgRecallMsg();
            msgRecallMsg.setMsgRemoteId(String.valueOf(talkRecord.getRemoteMsgId()));
            msgRecallMsg.setMessageId(talkRecord.getId());

            // 构建trigger对象
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(msgRecallMsg, MicaTriggerType.TRIGGER_MSG_RECALL, item -> {
                item.setReqId(msgRecallMsg.getMessageId());
                item.setDeviceId(talkSession.getDeviceId());
                item.setDeviceType(talkSession.getDeviceType());
            });
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            //
            redisTemplate.opsForValue().set(String.format(RECALL_KEY, talkRecord.getId()), talkRecord.getId(), 5, TimeUnit.MINUTES);

            return SResultMsg.success(content, "消息撤回中");
        } catch (Exception e) {
            log.error("消息撤回失败", e);
            throw new BusinessException("消息撤回失败, 请稍后重试");
        }
    }

    @Override
    public boolean checkMsg(RRecallMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.allNotNull(baseMsg.getStaffId(), baseMsg.getTalkSessionId(), baseMsg.getRecordId());
    }

    @Override
    public Class<RRecallMsg> msgClass() {
        return RRecallMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_recall_msg;
    }
}
